using Ay.Framework.WPF.Controls;
using MPSystem.Models;
using Base.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;
using Ay.Framework.WPF;
using MPSystem.Views.YFQ;
using Base.DAL;
using System.IO;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage_History.xaml 的交互逻辑
    /// 综采工作阻力历史数据分析曲线图
    /// </summary>
    public partial class ZCYLPage_History : Page
    {
        Common common = new Common();
        public static ZCYLPage_History Me = null;
        public static int cqbh=0,gzmbh = 0;
        private DataZcService dzs = new DataZcService();
        private List<double> P1 = new List<double>() { 10, 34.6, 60, 80 };
        private List<double> P2 = new List<double>() { 11, 54, 70, 80 };
        private List<double> P3 = new List<double>() { 13, 45, 70, 90 };
        private List<string> test = new List<string>() { "正常", "正常1", "正常1", "正常2" };
        private List<double> P12 = new List<double>();
        private List<string> S = new List<string>() { "正常" };
        private List<double> F1 = new List<double>();
        private List<double> F2 = new List<double>();
        private List<double> F3 = new List<double>();
        private List<double> F12 = new List<double>();
        private List<double> Freq = new List<double>();
        private List<DateTime> T = new List<DateTime>();
        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set { _IsBusy = value; }
        }
        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private string ComanpyName = "";
        private bool FirstReflash = true;

        private string dtStart = "", dtEnd = "", wz = "", hSpan = "", MPa = "", sfzj = "0", stat = "";
        private int bh = 0;
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();

        public ZCYLPage_History()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
            Me = this;
        }

        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;
            var rcq = ConfigService.GetCQ(true);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            combcq.ItemsSource = rcq;
            combcq.SelectedIndex = 0;
            //工作面
            var rgzm = ConfigService.GetGZM(rcq.ElementAt(0).CQBH);
            combgzm.ItemsSource = common.LoadCombox_IECobx(rgzm);
            if(rgzm.Count()>0) combgzm.SelectedIndex = 1;

            ComanpyName = common.GetCompanyName();
            T_CompanyName.Text = ComanpyName + "综采工作阻力历史数据分析曲线图";

        }

        private void LayoutRoot_load(object sender, EventArgs e)
        {
            //SycnReflash();


        }
        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            SycnReflash();
        }


        /// <summary>
        /// 后台加载
        /// </summary>
        void SycnReflash()
        {
            var cond = ZCYLPage_History_Condition.Me.Cond;
            if (cond.Count == 0) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                {
                    bh = int.Parse(cond["bh"]);
                    wz = cond["wz"];
                    sfzj = cond["sfzj"];
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    hSpan = cond["hSpan"];
                    stat = cond["stat"];
                    MPa = cond["MPa"];

                    int cq = 0, gzm = 0;//测区，工作面
                    try
                    {
                        cq = int.Parse(combcq.SelectedValue.ToString());
                        gzm = int.Parse(combgzm.SelectedValue.ToString());
                    }
                    catch
                    {
                    }
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd) + new TimeSpan(23, 59, 59);

                    int s = 0, s1 = 1, s2 = 2, s3 = 4, s4 = 8, s5 = 16;
                    List<List<DateTime>> valuex = new List<List<DateTime>>();//横轴
                    Dictionary<string, List<double>> valuey = new Dictionary<string, List<double>>();//序列名-纵轴
                    //获取原始数据
                    DateTime last = DateTime.Now;
                    if (bh > 0 && wz == "")
                    {
                        Console.WriteLine("获取原始数据");
                        var r = dzs.CurveNormal(cq,gzm, bh, db, de);
                        Console.WriteLine("原始数据计算完毕，用时" + (DateTime.Now - last).TotalSeconds);
                        //CurveZc rt = new DataZcService().CurveNormal(1, 1, new DateTime(2017, 12, 1), new DateTime(2017, 12, 2));
                        //rt.T为时间，rt.P1为左柱

                        P1 = r.P1;
                        P2 = r.P2;
                        P3 = r.P3;
                        P12 = r.P12;
                        S = r.S;
                        T = r.T;
                        F1 = r.F1;
                        F1 = r.F2;
                        F1 = r.F3;
                        F12 = r.F12;
                        Freq = r.Freq;

                        //加入原始数据
                        s = int.Parse(sfzj);
                        if (s == 0)//整架
                        {
                            valuex.Add(T);
                            valuey.Add("整架", MPa == "MPa" ? P12 : F12);
                        }
                        else
                        {
                            if ((s & s1) > 0)//P1
                            {
                                valuex.Add(T);
                                valuey.Add("通道1", MPa == "MPa" ? P1 : F1);
                            }
                            if ((s & s2) > 0)//P2
                            {
                                valuex.Add(T);
                                valuey.Add("通道2", MPa == "MPa" ? P2 : F2);
                            }
                            if ((s & s3) > 0)//P3
                            {
                                valuex.Add(T);
                                valuey.Add("通道3", MPa == "MPa" ? P3 : F3);
                            }
                        }
                    }
                    else
                    {
                        /*Console.WriteLine("获取原始数据");
                        var r = dzs.CurveNormal(cq, gzm, wz, db, de);
                        Console.WriteLine("原始数据计算完毕，用时" + (DateTime.Now - last).TotalSeconds);
                        //CurveZc rt = new DataZcService().CurveNormal(1, 1, new DateTime(2017, 12, 1), new DateTime(2017, 12, 2));
                        //rt.T为时间，rt.P1为左柱

                        P1 = r.P1;
                        P2 = r.P2;
                        P3 = r.P3;
                        P12 = r.P12;
                        S = r.S;
                        T = r.T;
                        F1 = r.F1;
                        F1 = r.F2;
                        F1 = r.F3;
                        F12 = r.F12;
                        Freq = r.Freq;

                        //加入原始数据
                        s = int.Parse(sfzj);
                        if (s == 0)//整架
                        {
                            valuex.Add(T);
                            valuey.Add("整架", MPa == "MPa" ? P12 : F12);
                        }
                        else
                        {
                            if ((s & s1) > 0)//P1
                            {
                                valuex.Add(T);
                                valuey.Add("通道1", MPa == "MPa" ? P1 : F1);
                            }
                            if ((s & s2) > 0)//P2
                            {
                                valuex.Add(T);
                                valuey.Add("通道2", MPa == "MPa" ? P2 : F2);
                            }
                            if ((s & s3) > 0)//P3
                            {
                                valuex.Add(T);
                                valuey.Add("通道3", MPa == "MPa" ? P3 : F3);
                            }
                        }*/
                    }
                    //加入加权数据
                    s = int.Parse(hSpan);
                    last = DateTime.Now;
                    if ((s & s1) > 0)
                    {
                        var w = dzs.CurveWeighted(cq, gzm, bh, wz, 2, db, de);
                        valuex.Add(w.T);
                        valuey.Add("2小时", MPa == "MPa" ? w.P12 : w.F12);
                    }
                    if ((s & s3) > 0)
                    {
                        var w = dzs.CurveWeighted(cq, gzm, bh, wz, 8, db, de);
                        valuex.Add(w.T);
                        valuey.Add("8小时", MPa == "MPa" ? w.P12 : w.F12);
                    }
                    if ((s & s5) > 0)
                    {
                        var w = dzs.CurveWeighted(cq, gzm, bh, wz, 24, db, de);
                        valuex.Add(w.T);
                        valuey.Add("24小时", MPa == "MPa" ? w.P12 : w.F12);
                    }
                    Console.WriteLine("加权数据计算完毕，用时" + (DateTime.Now - last).TotalSeconds);
                    //计算均值和方差
                    last = DateTime.Now;
                    double avg = 0, std = 0;
                    s = int.Parse(stat);
                    if (wz == "" && (s & s1) > 0)
                    {
                        avg = dzs.CurveAvg(cq, gzm, bh, db, de, MPa == "MPa");
                    }
                    if (wz == "" && ((s & s2) > 0 || (s & s3) > 0))
                    {
                        std = dzs.CurveStd(cq, gzm, bh, db, de, MPa == "MPa");
                    }
                    Console.WriteLine("均值方差计算完毕，用时" + (DateTime.Now - last).TotalSeconds);
                    //更新上限、下限、报警值
                    View_ZC_INI_CS cs = Db.Find<View_ZC_INI_CS>("SELECT * FROM View_ZC_INI_CS WHERE CQBH=@cqbh", new { cqbh = cq });
                    if (cs != null)
                    {
                        UpperLimit = cs.YLSX;
                        LowLimit = cs.YLXX;
                    }
                    if (valuey.Count > 0)
                        CreateChartColumn("历史工作阻力", valuex, valuey, MPa, int.Parse(stat), avg, std);


                });
                //CreateChartColumn("测试", strListx, strListy);
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI
                busyin.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin.IsBusy = true;
            worker.RunWorkerAsync();
        }

        private DataSeries markers=new DataSeries();

        public void CreateChartColumn(string name, List<List<DateTime>> valuex, Dictionary<string, List<double>> valuey, string dw, int stat = 0, double avg = 0, double std = 0)
        {            
            chart.Series.Clear();
            chart.TrendLines.Clear();

            #region 标注功能
            if (FirstReflash)
            {
                markers.XValueType = ChartValueTypes.DateTime;
                markers.XValueFormatString = "yyyy-MM-dd HH:mm:ss";
                markers.ToolTipText = "点击移除此标注";
                markers.RenderAs = RenderAs.Point;
                markers.ShowInLegend = false;
            }
            isPick = false;
            chart.IndicatorEnabled = false;
            markers.DataPoints.Clear();
            chart.Series.Add(markers);            
            #endregion

            DateTime last = DateTime.Now;
            if (FirstReflash)
            {
                //设置图标的宽度和高度
                //chart.Width = 580;
                //chart.Height = 380;

                //是否启用打印和保持图片
                chart.ToolBarEnabled = true;

                //设置图标的属性
                chart.ScrollingEnabled = false;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示

                //创建一个标题的对象
                Title title = new Title();

                //设置标题的名称
                title.Text = Name;
                title.Padding = new Thickness(0, 10, 5, 0);

                //向图标添加标题
                chart.Titles.Add(title);
                //初始化一个新的Axis
                Axis xAxis = new Axis();
                xAxis.Enabled = true;
                AxisLabels xLabel = new AxisLabels();
                xLabel.Angle = -45;
                xAxis.AxisLabels = xLabel;
                //设置Axis的属性
                //图表的X轴坐标按什么来分类，如时分秒
                xAxis.IntervalType = IntervalTypes.Hours;
                //图表的X轴坐标间隔如2,3,20等，单位为xAxis.IntervalType设置的时分秒。
                //xAxis.Interval = 2;
                //设置X轴的时间显示格式为7-10 11：20           
                xAxis.ValueFormatString = "yyyy-MM-dd HH:mm:ss   ";
                //xAxis.ValueFormatString = "yy-MM-dd HH:mm";
                //给图标添加Axis
                chart.AxesX.Add(xAxis);

                // 创建一个新的数据线。               
                //DataSeries dataSeries = new DataSeries();

                //// 设置数据线的格式
                //dataSeries.RenderAs = RenderAs.StackedColumn;//柱状Stacked
                Console.WriteLine("图标基本框架绘制完毕，用时" + (DateTime.Now - last).TotalSeconds);
                
                FirstReflash = false;
            }
            //绘制上限、下限
            if (dw == "MPa")
            {
                TrendLine tl = new TrendLine();
                tl.Value = UpperLimit;
                tl.LineThickness = 1;
                tl.LabelText = string.Format("上限{0:N1}", UpperLimit);
                tl.LineColor = new SolidColorBrush(Colors.LightPink);
                chart.TrendLines.Add(tl);

                TrendLine t2 = new TrendLine();
                t2.Value = LowLimit;
                t2.LineThickness = 1;
                t2.LabelText = string.Format("下限{0:N1}", LowLimit);
                t2.LineColor = new SolidColorBrush(Colors.LightBlue);
                chart.TrendLines.Add(t2);
            }
            chart.AxesY.Clear();
            Axis yAxis = new Axis();
            //设置图标中Y轴的最小值永远为0           
            yAxis.AxisMinimum = 0;
            yAxis.AxisMaximum = dw == "MPa" ? 60 : 20000;
            yAxis.Suffix = dw;
            chart.AxesY.Add(yAxis);
            //创建第一个DataSeries
            last = DateTime.Now;
            Color[] colors = new Color[] { Colors.Black, Colors.Green, Colors.Red, Colors.Blue, Colors.Yellow };
            for (int ii = 0; ii < valuex.Count; ii++)
            {
                List<DateTime> vx = valuex[ii];
                string label = valuey.Keys.ElementAt(ii);
                List<double> vy = valuey[label];

                DataSeries oneDataSeries = new DataSeries();
                oneDataSeries.XValueType = ChartValueTypes.DateTime;
                oneDataSeries.LabelEnabled = false;
                //oneDataSeries.LabelText = "#YValue";
                oneDataSeries.LegendText = label;
                oneDataSeries.XValueFormatString = "yyyy-MM-dd HH:mm:ss";
                oneDataSeries.YValueFormatString = "0.0'"+dw+"'";
                //oneDataSeries.ToolTipText = "测定时间：#XValue\r\n#YValue";
                oneDataSeries.RenderAs = RenderAs.QuickLine;//折线
                oneDataSeries.MarkerEnabled = false;
                oneDataSeries.LineThickness = 1;
                oneDataSeries.Color = new SolidColorBrush(colors[ii % 5]);
                
                //创建第一个DataSeries的DataPoint
                DataPoint oneDataPoint = null;
                DateTime lastDt = default(DateTime);
                for (int i = 0; i < vy.Count; i++)
                {
                    oneDataPoint = new DataPoint();
                    lastDt = vx[i];
                    oneDataPoint.XValue = vx[i];
                    oneDataPoint.YValue = vy[i];
                    oneDataSeries.DataPoints.Add(oneDataPoint);
                }
                Console.WriteLine("数据转换完毕，用时" + (DateTime.Now - last).TotalSeconds);
                last = DateTime.Now;
                chart.Series.Add(oneDataSeries);
                Console.WriteLine("数据绘制完毕，用时" + (DateTime.Now - last).TotalSeconds);
            }
            last = DateTime.Now;
            //统计均值和方差
            int s = 0, s1 = 1, s2 = 2, s3 = 4, s4 = 8, s5 = 16;
            s = stat;
            if ((s & s1) > 0)
            {
                TrendLine tl = new TrendLine();
                tl.Value = avg;
                tl.LineThickness = 2;
                tl.LabelText = string.Format("P{0:N1}", tl.Value); 
                tl.LineColor = new SolidColorBrush(Colors.LightPink);
                chart.TrendLines.Add(tl);
            }
            if ((s & s2) > 0)
            {
                TrendLine tl = new TrendLine();
                tl.Value = avg + std;
                tl.LineThickness = 2;
                tl.LabelText = string.Format("P+σ{0:N1}", tl.Value);
                tl.LineColor = new SolidColorBrush(Colors.LightPink);
                chart.TrendLines.Add(tl);
            }
            if ((s & s3) > 0)
            {
                TrendLine tl = new TrendLine();
                tl.Value = avg + 2 * std;
                tl.LineThickness = 2;
                tl.LabelText = string.Format("P+2σ{0:N1}", tl.Value);
                tl.LineColor = new SolidColorBrush(Colors.LightPink);
                chart.TrendLines.Add(tl);
            }
            Console.WriteLine("上限下限绘制完毕，用时" + (DateTime.Now - last).TotalSeconds);
            

            //将生产的图表增加到Grid，然后通过Grid添加到上层Grid.           
            //Grid gr = new Grid();
            //gr.Children.Add(chart);
            //XX.Children.Add(gr);
        }

        private bool isPick = false;
        private void Chart_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if(!MPSystem.SESSIONS.ShowMenu || chart.Series.Count<2 || chart.Series[1].DataPoints.Count==0)
            {
                return;
            }
            ContextMenu menu = new ContextMenu();
            MenuItem menuItem1 = new MenuItem();
            menuItem1.Header = isPick?"取消标记": "标记";
            menuItem1.Click += new RoutedEventHandler((s, ee) => {
                isPick = !isPick;
                chart.IndicatorEnabled = isPick;
                if(!isPick)
                {
                    markers.DataPoints.Clear();
                }
            });
            menu.Items.Add(menuItem1);
            
            MenuItem menuItem2 = new MenuItem();
            menuItem2.Header = "导出标记";
            menuItem2.IsEnabled = markers.DataPoints.Count > 0;
            menuItem2.Click += new RoutedEventHandler((s, ee) => {

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".txt";
                dlg.Filter = "txt file|*.txt";
                dlg.CheckFileExists = false;
                if (dlg.ShowDialog() == true)
                {
                    //排序
                    List<DataPoint> sorted = markers.DataPoints.ToList();
                    sorted.Sort((x, y)=>
                    {
                        return ((DateTime)x.XValue).CompareTo(y.XValue);
                    });
                    FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.NewLine = Environment.NewLine;
                    foreach (var dp in sorted)
                    {
                        sw.WriteLine(((DateTime)dp.XValue).ToString("yyyy-MM-dd HH:mm:ss"));
                        sw.WriteLine(dp.YValue.ToString("f1")+ MPa);
                    }
                    sw.Flush();
                    sw.Close();
                    AyMessageBox.Show("导出完毕！");
                }
            });
            menu.Items.Add(menuItem2);
            chart.ContextMenu = menu;
        }

        private void Chart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //0：空 1：辅助标记系列 2：原始数据
            if (!isPick || chart.ToolTips.Count < 2 || !chart.ToolTips[2].IsVisible || chart.ToolTips[2].Text == "")
            {
                return;
            }
            string[] tips = chart.ToolTips[2].Text.Split(new char[] { ',' });
            DataPoint ptClick = new DataPoint();
            ptClick.XValue = DateTime.Parse(tips[0]);
            ptClick.YValue = double.Parse(tips[1].Replace(MPa, ""));
            foreach (var pt in markers.DataPoints)
            {
                if (pt.XValue.Equals(ptClick.XValue) && pt.YValue == ptClick.YValue)
                {
                    try { markers.DataPoints.Remove(pt); } catch (Exception ex) { }
                    return;
                }
            }
            //ptClick.MouseLeftButtonDown += new MouseButtonEventHandler((s, ee) => {
            //    //接收到当前被点击的LengendText的值 
            //    DataPoint dpoint = s as DataPoint;
            //});
            markers.DataPoints.Add(ptClick);
        }

        private void Combgzm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combgzm.SelectedValue == null) return;
        }

        /// <summary>
        /// 高级查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnH_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("检测报表--高级查询", "/Views/YFQ/ZCYLPage_History_Condition.xaml", 600, 500);
        }
        /// <summary>
        /// 附加信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAttac_Click(object sender, RoutedEventArgs e)
        {
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("检测报表--附加信息", "/Views/YFQ/ZCYLPage_Attac.xaml", 600, 500);
        }
        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing;
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else
            {
                ZCYLPage_History_Condition.Me.LoadBH();
            }
            window.ShowDialog();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            ZCYLPage_History_Condition.Me.UpdateCond();
            window.Hide();
            Me.SycnReflash();
            e.Cancel = true;
        }


        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            var gzmSource = ConfigService.GetGZM(cqbh);
            combgzm.ItemsSource = common.LoadCombox_IECobx(gzmSource);
            if (gzmSource.Count() > 0) combgzm.SelectedIndex = 1;
        }
    }
}
